﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MS.InformationManagement.Core.Support;
using office = Microsoft.Office.DocumentManagement.DocumentSets;
using MS.InformationManagement.DAL.DocumentCenter;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;
using System.Collections;

namespace MS.InformationManagement.BLL.AddRadicadoToExpediente
{
    public class AddToExpediente
    {

        public void Include(string radicadoId, string expedienteId, string listName)
        {
            Guid siteID = SPContext.Current.Site.ID;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite overridenSite = new SPSite(siteID))
                {
                    using (SPWeb overridenWeb = overridenSite.OpenWeb())
                    {
                        overridenWeb.AllowUnsafeUpdates = true;
                        var expediente = RadicadosHelper.GetExpedientById(expedienteId, overridenWeb);
                        office.DocumentSet radicado = RadicadosHelper.GetDocumentSetById(int.Parse(radicadoId), listName, overridenWeb);
                        radicado.Folder.Item[CustomSiteColumns.FIELD_EXPEDIENTE_ID] = expedienteId;
                        radicado.Folder.Item[CustomSiteColumns.FIELD_CURRENT_ACTION] = "MoveTo";
                        radicado.Log(string.Empty, DateTime.Now, Support.Enums.TraceableOperation.Incluido, SPContext.Current.Web.CurrentUser.LoginName, string.Format("Incluido al expediente {0}" , expedienteId));
                        radicado.Folder.Item.Update();
                        radicado.Folder.Update();
                        SPContentTypeId currentContentType = expediente.ParentList.ContentTypes[radicado.ContentType.Name].Id;
                        SPFolder sectionLibraryName = expediente.Item.ParentList.RootFolder;
                        radicado.Folder.MoveTo(sectionLibraryName.Url + "/" + expedienteId + "/" + radicado.Folder.Name);

                        //Actualiza el usuario en la lista de distribucion interna
                        SPList targetList = null;
                        targetList = overridenWeb.Lists.TryGetList(GlobalConstants.LIST_DISTRIBUCION);

                        SPQuery query = new SPQuery();
                        query.ViewAttributes = "Scope='RecursiveAll'";
                        query.Query = string.Concat("<Where>",
                                                        "<Eq>",
                                                            "<FieldRef Name='Document_Radicado' />",
                                                            "<Value Type='Text'>",
                                                              radicado.Folder.Name,
                                                            "</Value>",
                                                        "</Eq>",
                                                    "</Where>");
                        SPListItemCollection splc = targetList.GetItems(query);

                        if (splc.Count > 0)
                        {
                            SPListItem item = splc[0];
                            item[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED] = expediente.Folder.Item[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED]; //radicado.Folder.Item[CustomSiteColumns.FIELD_EXPEDIENTE_ASSIGNED];
                            item.Update();
                        }

                        overridenWeb.AllowUnsafeUpdates = false;
                        //this.MoveDocumentSet(radicado, expediente.Folder);
                        this.UpdateContentType(currentContentType, sectionLibraryName.DocumentLibrary.Title, radicado.Folder.Item.ID, expedienteId, overridenWeb);
                    }
                }
            });
        }

        public Expediente GetExpediente(string expedienteId)
        {
            //Get Expediente List
            string expedienteList = RadicadosHelper.GetListNameForExpedientById(expedienteId);



            
            
            //Getting expediente data
            if (string.IsNullOrEmpty(expedienteList))
                return null;
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                var expediente = (from exp in dc.GetList<Expediente>(expedienteList)
                                  where exp.NúmeroExpediente == expedienteId
                                  select exp).FirstOrDefault();
                return expediente;
            }
        }

        protected void UpdateContentType(SPContentTypeId contentType, Guid listId, int itemId, string expedienteId)
        {
            SPFolder currentFolder = SPContext.Current.Web.Lists[listId].GetItemById(itemId).Folder;
            currentFolder.Item[SPBuiltInFieldId.ContentTypeId] = contentType;
            UpdateVolume(ref currentFolder, expedienteId);
            currentFolder.Item.Update();
            currentFolder.Update();
        }

        protected void UpdateContentType(SPContentTypeId contentType, string listName, int itemId, string expedienteId, SPWeb web)
        {
            SPList targetList = web.Lists.TryGetList(listName);
            if (targetList == null) { throw new Exception(string.Format("La lista {0} no existe", listName)); }

            SPListItem element = targetList.GetItemById(itemId);
            if (element == null) { throw new Exception(string.Format("No existe un item con id {0} en la lista  {1}", itemId, listName)); }
            SPFolder currentFolder = element.Folder;
            currentFolder.Item[SPBuiltInFieldId.ContentTypeId] = contentType;
            currentFolder.Item[CustomSiteColumns.FIELD_VOLUME_ID] = UpdateVolume(ref currentFolder, expedienteId, web);
            web.AllowUnsafeUpdates = true;
            currentFolder.Item.Update();
            currentFolder.Update();
            web.AllowUnsafeUpdates = false;
        }

        protected void UpdateVolume(ref SPFolder currentFolder, string expedienteId)
        {
            Core.TomoActions.TomoActions coreTomo = new Core.TomoActions.TomoActions();
            Tomo currentTomoEntity = coreTomo.getVolumeIfExists(expedienteId);
            currentFolder.Item[CustomSiteColumns.FIELD_VOLUME_ID] = currentTomoEntity.Id;
            coreTomo.UpdateDateInVolume((int)currentTomoEntity.Id);
        }

        protected string UpdateVolume(ref SPFolder currentFolder, string expedienteId, SPWeb web)
        {
            Core.TomoActions.TomoActions coreTomo = new Core.TomoActions.TomoActions();
            Tomo currentTomoEntity = coreTomo.getVolumeIfExists(expedienteId, web);
            //currentFolder.Item[CustomSiteColumns.FIELD_VOLUME_ID] = currentTomoEntity.Id;
            coreTomo.UpdateDateInVolume((int)currentTomoEntity.Id, web);
            return currentTomoEntity.Id.ToString();
        }

        private void MoveDocumentSet(office.DocumentSet currentDocument, SPFolder targetFolder)
        {
            SPContentTypeId currentContentTypeId = currentDocument.Folder.Item.ContentTypeId;
            byte[] documentSetData = currentDocument.Export();
            string documentSetName = currentDocument.Item.Name;
            Hashtable properties = currentDocument.Folder.Properties;
            office.DocumentSet.Import(documentSetData, documentSetName, targetFolder);
        }

        public string GetRadicadoNumber(int radicadoId, string listName)
        {
            SPList targetList = SPContext.Current.Web.Lists.TryGetList(listName);
            if (targetList == null) { throw new Exception(string.Format("La biblioteca de usuario {0} no existe.", listName)); }
            SPListItem targetDocument = targetList.GetItemById(radicadoId);
            if (targetDocument == null) { throw new Exception(string.Format("No existe documento con id {0} en la biblioteca {1}", listName, radicadoId)); }
            return targetDocument[CustomSiteColumns.FIELD_DOCUMENT_RADICADO].ToString();
        }

    }
}
